<template>
  <div>
    <div class="box-border p-12px">
      <div>
        <SubTitle title="基本信息" />
        <el-descriptions :column="descInfo.column">
          <el-descriptions-item
            :label="item.label"
            v-for="(item, index) in descInfo.columns"
            :key="index"
          >
            <span v-if="item.key == 'fileName'"
              >{{ descInfo.data.fileName || '--' }}
              <el-button type="text" @click="downloadFile">下载</el-button></span
            >
            <span v-else>{{ descInfo.data[item.key] || '--' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="mt-16px">
        <SubTitle title="分类分级信息">
          <!-- <el-button
            link
            type="primary"
            class="ml-12px"
            @click="openSample"
            v-if="props.params.dataType !== 'schema'"
            >查看抽样数据</el-button
          > -->
        </SubTitle>
        <div class="mt-12px">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column label="" prop="title" />
            <el-table-column label="分类">
              <template #default="scope">
                {{
                  scope.row.title === '自动生成'
                    ? descInfo.data.classificationName
                    : descInfo.data.handClassificationName
                }}
              </template>
            </el-table-column>
            <el-table-column label="分级">
              <template #default="scope">
                {{
                  scope.row.title === '自动生成'
                    ? descInfo.data.levelName
                    : descInfo.data.handLevelName
                }}
              </template>
            </el-table-column>
            <el-table-column label="重要程度">
              <template #default="scope">
                {{
                  scope.row.title === '自动生成'
                    ? descInfo.data.importance
                    : descInfo.data.handImportance
                }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-descriptions column="1" class="mt-16px">
          <el-descriptions-item label="敏感期限">
            {{ descInfo.data.sensitiveDeadline == '2' ? '指定期限' : '默认期限' }}
          </el-descriptions-item>
          <el-descriptions-item label="到期时间">
            {{ descInfo.data.deadlineTime || '--' }}
          </el-descriptions-item>
          <el-descriptions-item label="到期后级别">
            {{ descInfo.data.deadlineLevelName || '--' }}</el-descriptions-item
          >
          <el-descriptions-item
            v-for="(extendItem, extendIndex) in extendList"
            :key="extendIndex"
            :label="extendItem.name"
            >{{ descInfo.data[`field${extendItem.index}`] || '--' }}</el-descriptions-item
          >
        </el-descriptions>
      </div>
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px">
        <div class="mt-16px">
          <SubTitle title="复核结果信息" />
          <el-form-item required label="复核状态：" prop="recheckStatus">
            <el-radio-group v-model="form.recheckStatus">
              <el-radio label="1">通过</el-radio>
              <el-radio label="0">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="复核分类意见：" />
          <el-table :data="recheckTable" style="width: 100%">
            <el-table-column label="">
              <template #default="scope">
                <div>{{ scope.row.title }} </div>
              </template>
            </el-table-column>
            <el-table-column label="分类">
              <template #default>
                <div>
                  <el-form-item required prop="recheckClassification">
                    <!-- <ns-input v-model="form.recheckClassification" clearable placeholder="请输入" /> -->
                    <el-cascader
                      ref="cascaderRef"
                      v-model="form.recheckClassification"
                      placeholder="请选择分类"
                      :props="classificationCascaderProps"
                      :options="classificationList"
                      filterable
                      clearable
                      @change="classificationChange"
                    />
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="分级">
              <template #default>
                <div>
                  <el-form-item required prop="recheckLevel">
                    <el-select v-model="form.recheckLevel" placeholder="请选择">
                      <el-option
                        v-for="item in levelList"
                        :key="item.levelCode"
                        :label="item.levelName"
                        :value="item.levelCode"
                      />
                    </el-select>
                  </el-form-item>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="重要程度">
              <template #default>
                <div>{{ form.recheckImportance }}</div>
              </template>
            </el-table-column>
          </el-table>

          <el-form-item label="敏感期限" required prop="recheckSensitiveDeadline" class="mt-16px">
            <el-radio-group v-model="form.recheckSensitiveDeadline">
              <el-radio label="1" key="1">默认期限</el-radio>
              <el-radio label="2" key="2">指定期限</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-form-item
              label="期限时间"
              required
              prop="recheckDeadlineTimeNum"
              v-if="form.recheckSensitiveDeadline === '2'"
            >
              <ns-input
                v-model="form.recheckDeadlineTimeNum"
                clearable
                type="number"
                placeholder="请输入整数时长"
                class="flex-1"
              />
            </el-form-item>
            <el-form-item
              required
              prop="recheckDeadlineTimeUnit"
              v-if="form.recheckSensitiveDeadline === '2'"
            >
              <el-select
                v-model="form.recheckDeadlineTimeUnit"
                placeholder="请选择时间单位"
                class="ml-12px flex-1"
              >
                <el-option
                  v-for="item in timeUnitOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-row>
          <el-form-item
            label="到期后敏感级别"
            prop="recheckDeadlineLevel"
            required
            v-if="form.recheckSensitiveDeadline === '2'"
          >
            <el-select v-model="form.recheckDeadlineLevel" placeholder="请选择">
              <el-option
                v-for="item in levelList"
                :key="item.levelCode"
                :label="item.levelName"
                :value="item.levelCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="复核说明" prop="recheckDesc" required>
            <ns-input
              v-model="form.recheckDesc"
              clearable
              type="textarea"
              placeholder="请输入复核说明"
              class="flex-1"
            />
          </el-form-item>
        </div>
        <div class="mt-16px">
          <SubTitle title="扩展字段内容" />
          <el-form-item
            v-for="(item, index) in extendList"
            :label="`${item.name}`"
            :prop="`recheckField${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <ns-input
              v-if="item.fillingMethod == '输入框'"
              v-model="form[`recheckField${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-if="item.fillingMethod == '选择器'"
              clearable
              v-model="form[`recheckField${item.index}`]"
              placeholder="请选择"
            >
              <el-option
                v-for="(option, optionIndex) in item.presetContentMap"
                :key="optionIndex"
                :label="option"
                :value="option"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Warning } from '@element-plus/icons-vue'
import SubTitle from '@/components/SubTitle/index.vue'
import { assetRecheck } from '@/api/assetList'
import { classificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { infoPage } from '@/api/dataStandards/info/index'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any

const formRef = ref()
const cascaderRef = ref()
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})
const classificationCascaderProps = ref({
  checkStrictly: true,
  label: 'cnName',
  value: 'id',
  children: 'children',
  emitPath: false
})

const form = ref({
  id: '',
  recheckClassification: '',
  recheckLevel: '',
  recheckImportance: '',
  recheckSensitiveDeadline: '',
  recheckDeadlineLevel: '',
  recheckDeadlineTimeNum: '',
  recheckDeadlineTimeUnit: '',
  recheckExtendContent: '',
  recheckStatus: '',
  recheckDesc: ''
})
const rules = {
  recheckStatus: [{ required: true, message: '复核状态不能为空', trigger: 'blur' }],
  recheckSensitiveDeadline: [{ required: true, message: '敏感期限不能为空', trigger: 'blur' }],
  recheckDeadlineTimeNum: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
  recheckDeadlineTimeUnit: [{ required: true, message: '时间单位不能为空', trigger: 'blur' }],
  recheckDeadlineLevel: [{ required: true, message: '到期后敏感级别不能为空', trigger: 'blur' }],
  recheckClassification: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  recheckLevel: [{ required: true, message: '分级不能为空', trigger: 'blur' }],
  recheckDesc: [{ required: true, message: '复核说明不能为空', trigger: 'blur' }]
}

const timeUnitOptions = [
  {
    label: '年',
    value: '年'
  },
  {
    label: '月',
    value: '月'
  },
  {
    label: '日',
    value: '日'
  }
]

const descInfo = reactive({
  column: 1,
  columns: [
    { label: '表名称：', key: 'table' },
    { label: '表描述：', key: 'remark' },
    { label: '所属库：', key: 'database' }
  ],
  data: {}
})

const tableData = [
  {
    title: '自动生成'
  },
  {
    title: '手动调整'
  }
]

const recheckTable = [
  {
    title: '复核意见'
  }
]

const extendList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])

const downloadFile = () => {
  window.open(descInfo.data.absolutePath)
}

const classificationChange = (e) => {
  console.log('e', e)
  if (e) {
    const checkedNode = cascaderRef.value.getCheckedNodes()
    if (checkedNode[0].data.levelCode) {
      form.value.recheckLevel = checkedNode[0].data.levelCode
    }
  }
}
watch(
  () => form.value.recheckLevel,
  (newValue) => {
    console.log('newValue', newValue)
    const levelItem = levelList.value.find((item) => item.levelCode == newValue)
    console.log('levelItem', levelItem)
    if (levelItem) {
      form.value.recheckImportance = levelItem.importance
    }
  }
)

const recheckFieldList = ref({})
const confirm = async () => {
  for (let i = 1; i <= 20; i++) {
    recheckFieldList.value[`recheckField${i}`] = form.value[`recheckField${i}`]
  }
  // 扩展字段
  form.value.recheckExtendContent = JSON.stringify(recheckFieldList.value)
  console.log('form.value', form.value)
  formRef.value.validate(async (valid) => {
    if (valid) {
      const data = await assetRecheck(form.value)
      console.log('data', data)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 获取模板扩展字段列表
const getInfoList = async () => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: props.params.template,
    display: '1'
  })
  extendList.value = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
}

// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async () => {
  const data = await classificationTree({
    standardId: props.params.template
  })
  classificationList.value = data
}

// 获取等级下拉列表
const levelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  console.log('data', data)
  levelList.value = data
}

const openSample = () => {
  if (props.params.dataType === 'column') {
    proxy?.$Drawer({
      params: {
        samples: props.params.samples
      },
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/columnSamples.vue')
    })
  } else if (props.params.dataType === 'file') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看抽样数据`,
      size: '30%',
      component: import('@/views/asset/assetList/components/fileSamples.vue')
    })
  } else if (props.params.dataType === 'table') {
    proxy?.$Drawer({
      params: props.params,
      title: `查看字段分级`,
      size: '30%',
      component: import('@/views/asset/assetList/components/tableSamples.vue')
    })
  }
}

onMounted(() => {
  getInfoList()
  getClassificationTree()
  getLevelList()
  descInfo.data = props.params
  const {
    id,
    recheckClassification,
    recheckLevel,
    recheckImportance,
    recheckSensitiveDeadline,
    recheckDeadlineLevel,
    recheckDeadlineTimeNum,
    recheckDeadlineTimeUnit,
    recheckExtendContent,
    recheckStatus,
    recheckDesc
  } = props.params
  form.value = {
    id,
    recheckClassification,
    recheckLevel,
    recheckImportance,
    recheckSensitiveDeadline,
    recheckDeadlineLevel,
    recheckDeadlineTimeNum,
    recheckDeadlineTimeUnit,
    recheckExtendContent,
    recheckStatus,
    recheckDesc
  }
  if (form.value.recheckExtendContent) {
    recheckFieldList.value = JSON.parse(form.value.recheckExtendContent)
  }
  for (let i = 1; i <= 20; i++) {
    form.value[`recheckField${i}`] = recheckFieldList.value[`recheckField${i}`]
  }
  if (props.params.dataType === 'column') {
    descInfo.column = 2
    descInfo.columns = [
      { label: '字段名称：', key: 'column' },
      { label: '字段类型：', key: 'columnType' },
      { label: '字段描述：', key: 'comment' },
      { label: '所属表：', key: 'table' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' }
    ]
  } else if (props.params.dataType === 'file') {
    descInfo.column = 1
    descInfo.columns = [
      { label: '文件名称：', key: 'fileName' },
      { label: '文件类型：', key: 'fileType' },
      { label: '文件大小：', key: 'fileSize' },
      { label: '文件路径：', key: 'absolutePath' }
      // { label: '文件哈希：', key: 'fileFingerprint' }
    ]
  }
})
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
